<template>
  <el-dialog
    v-model="demandDetailsDisplay"
    title="需求详情"
    width="1000"
    destroy-on-close
  >
    <el-container>
      <el-container style="border-right: 2px solid gainsboro">
        <el-main>
          <el-form
            label-width="auto"
            :model="demandForm"
            class="demo-form-inline"
          >
            <el-form-item label="需求名称">
              <el-input
                v-model="demandForm.name"
                placeholder="请输入需求名称"
                clearable
                style="max-width: 240px"
              />
            </el-form-item>
            <el-form-item label="负责人">
              <user-selector v-model="demandForm.chargeId" />
            </el-form-item>
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="demandForm.startTime"
                style="max-width: 240px"
                format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="demandForm.endTime"
                style="max-width: 240px"
                format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item label="需求描述">
              <el-input
                v-model="demandForm.description"
                style="max-width: 240px"
                type="textarea"
              />
            </el-form-item>
            <div>
              <el-form-item label="需求相关文件">
                <el-upload
                  v-model:file-list="attachmentsFileList"
                  :http-request="handleFileUpload"
                  style="width: 240px"
                  multiple
                >
                  <el-button type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </div>
            <el-form-item label="项目进展状态">
              <el-select v-model="demandForm.status" style="max-width: 150px">
                <el-option
                  v-for="(v, i) in demandStatus"
                  :key="i"
                  :value="i"
                  :label="v"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="优先级">
              <el-select v-model="demandForm.priority" style="max-width: 150px">
                <el-option
                  v-for="(v, i) in priorityStatus"
                  :key="i"
                  :value="i"
                  :label="v"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <h4>子需求或任务</h4>
          <el-table
            :data="demandChildrenTable"
            border
            style="width: 100%; margin-top: 20px"
            row-key="uuid"
          >
            <el-table-column prop="name" label="需求名称">
              <template v-slot="scope">
                <el-input v-if="scope.row.edit" v-model="scope.row.name" />
                <span v-else>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="charge.id" label="负责人">
              <template v-slot="scope">
                <user-selector
                  v-model="scope.row.chargeId"
                  :disabled="!scope.row.edit"
                />
              </template>
            </el-table-column>
            <el-table-column label="类型">
              <template v-slot="scope">
                <el-select v-model="scope.row.type" :disabled="!scope.row.edit">
                  <el-option
                    v-for="(v, i) in demandType"
                    :key="i"
                    :value="i"
                    :label="v"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  v-if="scope.row.edit"
                  type="primary"
                  @click="saveChildDemand(scope.row)"
                >
                  保存
                </el-button>
                <template v-else>
                  <el-button
                    type="primary"
                    @click="
                      () => {
                        childDemandId = scope.row.id;
                        childDisplay = true;
                      }
                    "
                    >详情</el-button
                  >
                </template>

                <el-button type="danger" @click="delChildren(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-button style="margin-top: 20px" @click="addChildren"
            >添加一项
          </el-button>
        </el-main>
      </el-container>
      <el-aside width="250px">
        <el-main>
          <div v-for="item in demandLogs" :key="item.id">
            <div>{{ item.createTime }}</div>
            {{ item.companyUser?.nickName }} {{ item.content }}
            {{ item.relateDemandName }}
          </div>
        </el-main>
      </el-aside>
    </el-container>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveDemand">保存</el-button>
      </div>
    </template>
  </el-dialog>
  <demand-dialog
    v-if="childDemandId"
    v-model="childDisplay"
    :demand-id="childDemandId"
  />
</template>

<script setup lang="ts">
import {
  demandStatus,
  demandType,
  priorityStatus
} from "@/constants/project.ts";
import UserSelector from "@/components/Selector/UserSelector.vue";
import { onMounted, ref, defineProps, watch, defineEmits } from "vue";
import {
  ProjectDemandActivityLogVo,
  type ProjectDemandChildrenListVo
} from "@/api/models";
import {
  createDemand,
  deleteDemand,
  demandChildren,
  demandDetails,
  demandLog,
  updateDemand
} from "@/api/demand.ts";
import { guid } from "@/utils/idUtils.ts";
import { uploadFile } from "@/api/file.ts";
import { ElMessage } from "element-plus";
import { stdTime } from "@/utils/time.ts";
let props = defineProps({
  demandId: {
    type: [String, Object],
    required: false
  },
  modelValue: {
    type: Boolean,
    default() {
      return false;
    }
  }
});
let emits = defineEmits(["update:modelValue"]);
async function saveDemand() {
  let { startTime, endTime } = demandForm.value;
  startTime = startTime ? stdTime(startTime) : undefined;
  endTime = endTime ? stdTime(endTime) : undefined;
  let res = await updateDemand({
    ...demandForm.value,
    startTime,
    endTime
  });
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: "保存成功"
    });
    demandDetailsDisplay.value = false;
    // detailsProjectDisplay.value = false;
    // getList();
  } else {
    ElMessage({
      type: "error",
      message: res.msg
    });
  }
}
let demandForm = ref({
  priority: 1,
  name: "",
  description: "",
  startTime: "",
  endTime: "",
  status: 0,
  type: 0
});
let demandDetailsDisplay = ref(false);
let demandLogs = ref<ProjectDemandActivityLogVo[]>([]);
let demandChildrenTable = ref<ProjectDemandChildrenListVo[]>([]);
async function openDemandDetails(id) {
  demandDetailsDisplay.value = true;
  let detailsRes = await demandDetails(id);
  demandForm.value = detailsRes.data;
  demandForm.value.chargeId = detailsRes.data.charge.id;
  let children = await demandChildren(id);
  demandChildrenTable.value = children.data.map(i => ({ ...i, uuid: guid() }));
  let logsRes = await demandLog(id);
  demandLogs.value = logsRes.data;
}
let childDemandId = ref("");
onMounted(() => {
  demandDetailsDisplay.value = props.modelValue;
});
watch(demandDetailsDisplay, nv => {
  if (nv) {
    openDemandDetails(props.demandId);
  }
  emits("update:modelValue", nv);
});
watch(props, nv => {
  demandDetailsDisplay.value = nv.modelValue;
});
async function delChildren(row) {
  if (!row.edit) {
    let res = await deleteDemand(row.id);
    if (res.code !== 200) {
      ElMessage({
        type: "error",
        message: res.msg
      });
      return;
    }
  }
  for (let i = 0; i < demandChildrenTable.value.length; i++) {
    if (demandChildrenTable.value[i].uuid === row.uuid) {
      demandChildrenTable.value.splice(i, 1);
      break;
    }
  }
}
function addChildren() {
  demandChildrenTable.value.push({ uuid: guid(), type: 0, edit: true });
}
async function handleFileUpload(file) {
  let res = await uploadFile(file.file);
  if (res.code === 200) {
    for (let item of attachmentsFileList.value) {
      if (item.uid == file.file.uid) {
        item.url = res.data.url;
      }
    }
    for (let item of attachmentsFileList.value) {
      if (item.uid == file.file.uid) {
        item.url = res.data.url;
      }
    }
  }
}
let attachmentsFileList = ref([]);
let childDisplay = ref(false);
async function saveChildDemand(row) {
  if (!row.name) {
    ElMessage({
      type: "error",
      message: "请填写需求名称"
    });
    return;
  }
  let res = await createDemand({ ...row, pid: props.demandId });
  if (res.code === 200) {
    row.edit = false;
  }
}
</script>
